/*
 * Creater:     柿子
 * CreateDate:  2022/12/28
 * Describe：   在线预览
 * */
import React, { Component } from 'react';
import { message, Modal } from 'antd';
import { Util } from 'tools';
import { httpConfig } from 'containers/config/httpConfig'
import FileViewer from 'react-file-viewer';

class FileOnlinePreview extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uploadUrl: '',
      fileLocalUrl: null,
      fileType: '',
      type: ''
    }
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
    let httpUrl = windowHost && (windowHost.indexOf('localhost') !== -1 || windowHost.indexOf('127.0.0.1') !== -1) ? httpConfig.ipDeault : windowHost;
    let uploadUrl = httpUrl + '/images/optomefile/';
    this.setState({ uploadUrl });
  }

  // 修改弹窗状态
  modifyVisible = (visible, fileData, type) => {
    visible && this.getFileData(fileData, type);
    this.setState({ visible, type }, () => {
      if (!this.state.visible) {
        const { fileLocalUrl } = this.state;
        window.URL = window.URL || window.webkitURL;
        fileLocalUrl && window.URL.revokeObjectURL(fileLocalUrl); // 清理内存
      }
    });
  }

  // 获取文件信息
  getFileData = (file, type) => {
    const { uploadUrl } = this.state;
    if (type === 'file') {
      let fileData = file && 'file' in file ? file.file?.originFileObj || {} : file?.originFileObj || file;
      let fileName = fileData?.name || '';
      window.URL = window.URL || window.webkitURL;
      this.setState({
        fileLocalUrl: window.URL.createObjectURL(fileData),
        fileType: fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length),
      })
    } else {
      let fileName = file?.name || '';
      this.setState({
        fileLocalUrl: uploadUrl + type,
        fileType: fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length),
      })
    }
  }

  // 预览错误
  handleError = Util.debounce((e) => {
    message.error('预览错误，请下载到本地查看')
  })

  // 下载
  handleFileDownload = () => {
    const { type, uploadUrl } = this.state;
    if (type === 'file') {
      message.info('暂不支持下载');
      return
    };
    type && (window.open(uploadUrl + type));
  }

  render() {
    const { fileLocalUrl, fileType, visible } = this.state;
    return (
      <Modal
        visible={visible}
        okText="下载"
        width="800px"
        title={<div className="flex">在线预览<span style={{ fontSize: '13px', fontWeight: 'normal', color: '#f26f6f' }}>【如预览异常，可点击下载按钮下载到本地查看】</span></div>}
        onOk={this.handleFileDownload}
        onCancel={() => this.modifyVisible(false)}
      >
        <div style={{ height: '60vh', overflow: 'auto' }}>
          {
            visible && fileLocalUrl && <FileViewer
              fileType={fileType}
              errorComponent={<div>预览错误，请下载到本地查看</div>}
              filePath={fileLocalUrl}
              onError={(e) => this.handleError(e)}
            />
          }
        </div>
      </Modal>
    )
  }
};

export default FileOnlinePreview;